package com.example.controller;

import com.example.dto.StorageDTO;
import com.example.exception.BaseException;
import com.example.feign.StorageFeignClient;
import com.example.model.api.Result;
import com.example.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("storage")
public class StorageController implements StorageFeignClient {

    @Autowired
    private StorageService storageService;

    @GetMapping
    public Result<String> demo(){
        return new Result<String>().ok("ok");
    }

    @PostMapping
    public Result<String> updateStorage(@RequestBody StorageDTO storageDto) {
        try {
            storageService.updateStorage(storageDto.getCommodityCode(), storageDto.getCount());
        } catch (Exception e) {
            // 抛出异常，feign会捕获到，并返回给调用方
            throw new BaseException("更新库存失败", HttpStatus.BAD_REQUEST);
            // 全局事务调用时，无法正常回滚，所以必须使用异常抛出，否则无法回滚
//            return new Result<String>().fail("更新库存失败");
        }
        return new Result<String>().ok("ok");
    }
}
